package com.danicsoft.daide.command;

import com.danicsoft.daide.token.StandardToken;
import com.danicsoft.daide.token.TokenGroup;
import com.danicsoft.daide.token.TokenMap;
import com.danicsoft.daide.token.TokenMap.Phases;

/**
 * Represents a turn (year and phase)
 * 
 * @author Daniel Yule (daniel.yule@gmail.com)
 * @version 1.0
 */
public class Turn implements IOTarget, Comparable<Turn> {

	/**
	 * The year of this turn.
	 */
	public int year;

	/**
	 * The phase of this turn.
	 */
	public StandardToken season;

	/**
	 * Create a new completely empty turn.
	 */
	public Turn() {}

	/**
	 * Create a new turn from the given data.
	 * 
	 * @param year
	 *        The year for this turn.
	 * @param season
	 *        The season for this turn.
	 */
	public Turn(int year, StandardToken season) {
		this.year = year;
		this.season = (StandardToken) season.clone();
	}

	public void doIO(TokenIO tokenIO, TokenGroup tokens) throws ParseException {
		TokenGroup thisGroup = tokenIO.subGroup(tokens);
		season = (StandardToken) tokenIO.doToken(thisGroup, season, TokenMap.phase);
		year = tokenIO.doInteger(thisGroup, year);
	}

	public IOTarget newInstance() {
		return new Turn();
	}

	@Override
	public String toString() {
		return season.toString() + ' ' + year;
	}

	@Override
	public Turn clone() {
		return new Turn(year, season);
	}

	/**
	 * Gets an integer corresponding to the ordering of the phases.
	 * 
	 * @return An ordering integer.l
	 */
	private int getPhaseOrder() {
		switch (season.getData()) {
			case Phases.SPR:
				return 0;
			case Phases.SUM:
				return 1;
			case Phases.FAL:
				return 2;
			case Phases.AUT:
				return 3;
			case Phases.WIN:
				return 4;
		}
		return 5;
	}

	public int compareTo(Turn o) {
		long myTurn =  ((long)(year * 5) + getPhaseOrder());
		long theirTurn =  ((long) o.year * 5) + o.getPhaseOrder();
		return (int) (theirTurn - myTurn);
	}

}